#!/usr/bin/python3
# encoding:utf8

import html
import os
import uuid
import platform
import time,datetime
from flask import Flask, render_template, request,session,redirect

import web.dao.ArticleDao as articledao
import web.dao.CaDao as cadao
import web.dao.ColumnDao as columndao
from web.entity.Article import Article

UP_LOAD = 'static/upload/image'
SAVE_PATH = '/static/upload/image'
DIR = os.path.join(os.getcwd(), UP_LOAD)

app = Flask(__name__)
app.config['SECRET_KEY'] = os.urandom(24)

@app.before_request
def before_req():
    url = request.path
    pass_list = ['/', '/login']
    suffix = url.endswith('.png') or url.endswith('.jpg') or url.endswith('.css') or url.endswith('.js')
    if url in pass_list or suffix:
        pass
    elif session.get('is_login') != 'true':
        return redirect("/")
    else:
        pass


@app.route('/upload', methods=['POST'])
def upload():
    fobject = request.files.get('f')
    uid = str(uuid.uuid1()).replace('-', '') + fobject.filename
    img_path = os.path.join(DIR, uid)
    fobject.save(img_path)
    save_path = os.path.join(SAVE_PATH, uid)
    return save_path

@app.route('/', methods=['GET'])
def indexdef():
    return render_template('login.html')

pwd_code = 'xcQ=WA'
@app.route('/login', methods=['GET'])
def indexlogin():
    pwd = request.args.get('pwd')
    pwds = pwd.split('_')
    dopwd = pwds[0][3: 7] + pwds[3]
    if(dopwd == pwd_code):
        session['is_login'] = 'true'
        return redirect("/main")
    return redirect("/")

@app.route('/clear', methods=['GET'])
def clearlogin():
    session['is_login'] = 'false'
    return redirect("/")

@app.route('/main', methods=['GET'])
def indexmain():
    menus = columndao.selectNotislable()
    lables = columndao.selectislable()
    cid = '0'
    if len(menus):
        cid = menus[0].id
    articles = articledao.selectArticleByCid(cid)
    return render_template('index.html', menus=menus, lables=lables, articles=articles)

@app.route('/index', methods=['GET'])
def index():
    menus = columndao.selectNotislable()
    lables = columndao.selectislable()
    cid = '0'
    if len(menus):
        cid = menus[0].id
    articles = articledao.selectArticleByCid(cid)
    return render_template('index.html', menus=menus, lables=lables, articles=articles)

@app.route('/find', methods=['GET'])
def selectArticle():
    parameter = request.args.get('parameter')
    menus = columndao.selectNotislable()
    lables = columndao.selectislable()
    articles = articledao.selectArticleFind(parameter)
    return render_template('index.html', menus=menus, lables=lables, articles=articles)


@app.route('/index/<id>/', methods=['GET'])
def selectArticleListByCol(id):
    menus = columndao.selectNotislable()
    lables = columndao.selectislable()
    if (id != '0'):
        articles = articledao.selectArticleByCid(id)
    else:
        articles = articledao.selectAllArticle()
    return render_template('index.html', menus=menus, lables=lables, articles=articles, col=id)


@app.route('/article/<id>/', methods=['GET'])
def selectOneArticle(id):
    article = articledao.selectArticleById(id)
    article.title = html.unescape(article.title)
    article.content = html.unescape(article.content)
    return render_template('detail.html', article=article)


@app.route('/article/create/<colid>/', methods=['GET'])
def articleCreate(colid):
    if len(colid) == '0':
        colid = '0'
    article = Article('', '', '', '1', datetime.date.today(), '1')
    column = columndao.selectColumnById(colid)
    submitUrl = '/article/create/save/'
    return render_template('article.html', article=article, submitUrl=submitUrl, column=column)


@app.route('/article/create/save/', methods=['POST'])
def articleCreateSave():
    title = html.escape(request.form.get('title'))
    content = html.escape(request.form.get('content'))
    sort = request.form.get('sort')
    time = request.form.get('time')
    end = request.form.get('end')
    colid = request.form.get('colid')
    lastid = articledao.createArticle(title, content, sort, time, end)
    cadao.intoRelation(colid, lastid)
    if colid != '0':
        cadao.intoRelation('0', lastid)
    return render_template('end.html')


@app.route('/article/update/<id>/', methods=['GET'])
def articleUpdate(id):
    article = articledao.selectArticleById(id)
    article.title = html.unescape(article.title)
    article.content = html.unescape(article.content)
    submitUrl = '/article/update/save/'
    return render_template('article.html', article=article, submitUrl=submitUrl, column=None)


@app.route('/article/update/save/', methods=['POST'])
def articleUpdateSave():
    id = request.form.get('id')
    title = html.escape(request.form.get('title'))
    content = html.escape(request.form.get('content'))
    sort = request.form.get('sort')
    time = request.form.get('time')
    end = request.form.get('end')
    articledao.updateArticle(id, title, content, sort, time, end)
    return render_template('end.html')


@app.route('/article/move/<aid>/', methods=['GET'])
def move(aid):
    cols = columndao.selectMoveColumn(aid)
    return render_template('move.html', cols=cols, aid=aid)


@app.route('/article/delete/<id>/', methods=['GET'])
def articleDeleteSave(id):
    articledao.deleteArticleById(id)
    return render_template('end.html')


@app.route('/article/move/save/', methods=['POST'])
def moveSave():
    aid = request.form.get('aid')
    cids = request.form.getlist('cids')
    columndao.moveColumnSave(aid, cids)
    return render_template('end.html')


@app.route('/col/', methods=['GET'])
def colPage():
    menus = columndao.selectNotislable()
    lables = columndao.selectislable()
    return render_template('column.html', menus=menus, lables=lables)


@app.route('/col/create/save/', methods=['POST'])
def colCreateSave():
    title = request.form.get('title')
    islabel = request.form.get('islabel')
    sort = request.form.get('sort')
    columndao.creatColumn(title, islabel, sort)
    return "ok"


@app.route('/col/update/save/', methods=['POST'])
def colUpdateSave():
    id = request.form.get('id')
    title = request.form.get('title')
    islabel = request.form.get('islabel')
    sort = request.form.get('sort')
    if (id != '0'):
        columndao.updatColumn(id, title, islabel, sort)
    return "ok"


@app.route('/col/delete/save/', methods=['POST'])
def colDeleteSave():
    id = request.form.get('id')
    if (id != '0'):
        columndao.deletColumnById(id)
    return "ok"


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)
